﻿namespace IntellectShop.Web2.Controllers
{
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Web.Mvc;
	using IntellectShop.Common;
	using IntellectShop.Web2.ViewModels;

	[IntellectShop.Web2.Code.NoCache]
	[IntellectShop.Web2.Code.HandleErrorWithELMAH]
	public class ScheduleController : Controller
	{
		//
		// GET: /Schedule/
		public ActionResult Index()
		{
			ScheduleNearestViewModel model = new ScheduleNearestViewModel();

			model.NearestGroupedCourses = new Dictionary<Common.Category, IDictionary<string, IEnumerable<Common.Course>>>();
			model.BaseDate = DateTime.Now.Date.AddDays(-DateTime.Now.Day).AddDays(1);

			Dictionary<Common.Category, List<Common.Course>> coursesGroupedByCategory = Common.Course.RetrieveCoursesByCategory(
				DateTime.Now.Date,
				model.BaseDate.AddMonths(Common.Schedule.MonthOfNearestCourses));

			foreach (Common.Category category in coursesGroupedByCategory.Keys)
			{
				List<Common.Course> courses = coursesGroupedByCategory[category];
				List<Common.Course> alreadyAddedCourses = new List<Common.Course>();

				Common.TagsSet tagsSet = Common.TagsSet.GetFavoritesTags(courses);
				tagsSet.Add(String.Empty);
				foreach (string tag in tagsSet)
				{
					IDictionary<string, IEnumerable<Common.Course>> taggedCourses;
					if (model.NearestGroupedCourses.ContainsKey(category))
					{
						taggedCourses = model.NearestGroupedCourses[category];
					}
					else
					{
						taggedCourses = new Dictionary<string, IEnumerable<Common.Course>>();
						model.NearestGroupedCourses.Add(category, taggedCourses);
					}

					IEnumerable<Common.Course> selectedCourses;
					if (!String.IsNullOrEmpty(tag))
					{
						selectedCourses = courses.Where(x => x.Tags != null && x.Tags.Contains(tag)).Except(alreadyAddedCourses);
					}
					else
					{
						selectedCourses = courses.Where(x => x.Tags == null || x.Tags.Count == 0);
					}

					if (selectedCourses != null && selectedCourses.Count() != 0)
					{
						List<Common.Course> list = selectedCourses.ToList();
						taggedCourses.Add(tag, list);
						alreadyAddedCourses.AddRange(list);
					}
				}
			}


			return View(model);
		}

		//
		// GET: /Schedule/Details/5
		public ActionResult Details(int courseID)
		{
			ScheduleViewModel model = new ScheduleViewModel();
			if (HttpContext.User.IsInRole(Globals.AdministratorRoleName))
			{
				model.Schedule = Common.Schedule.RetrieveByCourseID(courseID);
			}
			else
			{
				model.Schedule = Common.Schedule.RetrieveByCourseIDAndPeriod(courseID, DateTime.Now.Date);
			}

			return View(model);
		}

		//
		// GET: /Schedule/Create
		[Authorize(Roles = Globals.AdministratorRoleName)]
		public ActionResult Create(int courseID)
		{
			Common.Course course = Common.Course.RetrieveByCourseID(courseID);
			var viewModel = new ScheduleCreateViewModel
			{
				Course = Common.Course.RetrieveByCourseID(courseID),
				CourseID = courseID,
				DurationDays = course.Duration.Days,
				DurationHoursInDay = course.Duration.Hours / course.Duration.Days,
				EventDate = DateTime.Now.Date,
				Note = String.Empty
			};

			return View(viewModel);
		}

		//
		// POST: /Schedule/Create
		[HttpPost]
		[Authorize(Roles = Globals.AdministratorRoleName)]
		public ActionResult Create(ScheduleCreateViewModel model, FormCollection collection)
		{
			Common.Course course = Common.Course.RetrieveByCourseID(model.CourseID);
			try
			{
				if (!ModelState.IsValid)
					throw new ArgumentException("Ошибка при заполнении полей для: ScheduleItem!");

				Common.Schedule schedule = course.Schedule;
				for (int i = 0; i < model.DurationDays; i++)
				{
					var key = model.EventDate.Date.AddDays(i);
					schedule.Remove(key);
					schedule.Add(key, new Common.ScheduleItem
					{
						CourseID = course.CourseID,
						DurationHours = model.DurationHoursInDay,
						EventDate = model.EventDate,
						Note = model.Note
					});
				}

				schedule.Save();
				return RedirectToAction("Details", "Course", new { id = course.CommodityID });
			}
			catch
			{
				var viewModel = new ScheduleCreateViewModel
				{
					Course = Common.Course.RetrieveByCourseID(model.CourseID),
					CourseID = model.CourseID,
					DurationDays = course.Duration.Days,
					DurationHoursInDay = course.Duration.Hours / course.Duration.Days,
					EventDate = DateTime.Now.Date,
					Note = String.Empty
				};

				return View(viewModel);
			}
		}

		//
		// GET: /Schedule/Edit/5
		[Authorize(Roles = Globals.AdministratorRoleName)]
		public ActionResult Edit(int scheduleItemID)
		{
			ScheduleEditViewModel model = new ScheduleEditViewModel();
			Common.ScheduleItem item = Common.ScheduleItem.RetrieveByScheduleItemID(scheduleItemID);
			model.ScheduleItem = item;
			model.Course = Common.Course.RetrieveByCourseID(item.CourseID);

			return View(model);
		}

		//
		// POST: /Schedule/Edit/5
		[HttpPost]
		[Authorize(Roles = Globals.AdministratorRoleName)]
		public ActionResult Edit(int scheduleItemID, FormCollection collection)
		{
			Common.ScheduleItem item = Common.ScheduleItem.RetrieveByScheduleItemID(scheduleItemID);
			DateTime key = item.EventDate;
			Common.Course corse = Common.Course.RetrieveByCourseID(item.CourseID);
			try
			{
				if (!ModelState.IsValid)
					throw new ArgumentException("Ошибка при заполнении полей для: ScheduleItem!");

				UpdateModel(item, "ScheduleItem");
				Common.Schedule schedule = corse.Schedule;
				schedule.Remove(key);
				schedule.Add(item.EventDate, item);
				schedule.Save();
				return RedirectToAction("Details", "Course", new { id = corse.CommodityID });
			}
			catch
			{
				var viewModel = new ScheduleEditViewModel
				{
					Course = corse,
					ScheduleItem = item
				};

				return View(viewModel);
			}
		}

		//
		// GET: /Schedule/Delete/5
		[Authorize(Roles = Globals.AdministratorRoleName)]
		public ActionResult Delete(int scheduleItemID)
		{
			Common.ScheduleItem item = Common.ScheduleItem.RetrieveByScheduleItemID(scheduleItemID);
			DateTime key = item.EventDate;
			Common.Course corse = Common.Course.RetrieveByCourseID(item.CourseID);
			try
			{
				if (!ModelState.IsValid)
					throw new ArgumentException("Ошибка при заполнении полей для: ScheduleItem!");

				Common.Schedule schedule = corse.Schedule;
				schedule.Remove(key);
				schedule.Save();
				return RedirectToAction("Details", "Course", new { id = corse.CommodityID });
			}
			catch
			{
				return RedirectToAction("Details", "Course", new { id = corse.CommodityID });
			}
		}

		//
		// POST: /Schedule/Delete/5
		[HttpPost]
		[Authorize(Roles = Globals.AdministratorRoleName)]
		public ActionResult Delete(int scheduleItemID, FormCollection collection)
		{
			try
			{
				// TODO: Add delete logic here

				return RedirectToAction("Index");
			}
			catch
			{
				return View();
			}
		}
	}
}
